package com.gdkj.sud;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.alibaba.fastjson.JSONObject;
import com.gdkj.constant.CommonConstant;
import com.gdkj.constant.RedisConstant;
import com.gdkj.enums.SudPushEventEnums;
import com.gdkj.util.HttpUtils;
import com.xjgks.common.exception.handler.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class SudUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public SudApiResult getAllApi(String env) throws Exception {
        String redisKey = RedisConstant.SUD_API_STR_PREFIX + env;
        String sudApiStr = stringRedisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isNotEmpty(sudApiStr)) {
            return JSONObject.parseObject(sudApiStr, SudApiResult.class);
        }

        // 加密数据更换为实际的AppId
        String data = CommonConstant.SUD_APP_ID;
        // 密码使用实际的AppSecret
        byte[] key = CommonConstant.SUD_APP_SECRET.getBytes();
        HMac mac = new HMac(HmacAlgorithm.HmacMD5, key);
        String appServerSign = mac.digestHex(data);
        String requestUrl = "https://sim-asc.sudden.ltd/";
        if ("pro".equals(env)) {
            requestUrl = "https://asc.sudden.ltd/";
        }
        requestUrl += appServerSign;
        sudApiStr = HttpUtils.doGet(requestUrl, 10);
        stringRedisTemplate.opsForValue().set(redisKey, sudApiStr, 1, TimeUnit.DAYS);
        if (StrUtil.isEmpty(sudApiStr)) {
           throw new RRException("获取sud接口异常，返回数据为空");
        }
        return JSONObject.parseObject(sudApiStr, SudApiResult.class);
    }

    public String getSign(SudPushEventRequest sudPushEventRequest) {
        // 应用ID
        String appId = CommonConstant.SUD_APP_ID;
        // 应用secret
        String appSecret = CommonConstant.SUD_APP_SECRET;
        // 请求时间戳（发送请求的时间戳）
        String timestamp = String.valueOf(sudPushEventRequest.getTimestamp());
        // 随机字符串 (自定义随机字符串)
        String nonce = UUID.randomUUID().toString().replace("-", "");

        String body = JSONObject.toJSONString(sudPushEventRequest);

        // 签名串
        String signContent = String.format("%s\n%s\n%s\n%s\n", appId, timestamp, nonce, body);
        // 签名值
        HMac hMac = new HMac(HmacAlgorithm.HmacSHA1, appSecret.getBytes());

        String signature = hMac.digestHex(signContent);
        return String.format("Sud-Auth app_id=\"%s\",timestamp=\"%s\",nonce=\"%s\",signature=\"%s\"", appId, timestamp, nonce, signature);
    }

    /**
     * sud踢人
     * @param uid
     * @param env
     * @return java.lang.String
     */
    public String kick(Long uid, String env) throws Exception {
        UserKickReqData userKickReqData = new UserKickReqData();
        userKickReqData.setKickedUid(String.format("%d", uid));

        return pushEvent(env, userKickReqData, SudPushEventEnums.KICK.getEvent());
    }

    /**
     * 用户加入
     * @param code
     * @param env
     * @param roomId
     * @return java.lang.String
     */
    public String userIn(String code, Long roomId, String env) throws Exception {
        // 组装请求数据
        UserInReqData userInReqData = new UserInReqData();
        userInReqData.setCode(code);
        userInReqData.setRoomId(String.format("%d", roomId));
        userInReqData.setMode(1);
        userInReqData.setLanguage("zh-CN");
        userInReqData.setSeatIndex(0);
        userInReqData.setSeatRandom(true);
        userInReqData.setTeamId(1);

        return pushEvent(env, userInReqData, SudPushEventEnums.USER_JOIN.getEvent());
    }

    /**
     * 用户加入
     * @param env
     * @param uid
     * @return java.lang.String
     */
    public String userOut(Long uid, String env) throws Exception {
        // 组装请求数据
        UserOutReqData userOutReqData = new UserOutReqData();
        userOutReqData.setUid(String.valueOf(uid));

        return pushEvent(env, userOutReqData, SudPushEventEnums.USER_OUT.getEvent());
    }

    /**
     * 游戏推送
     * @param env
     * @param data
     * @param event
     * @return
     * @throws Exception
     */
    public String pushEvent(String env, Object data, String event) throws Exception {
        // 1. 获取接口地址
        SudApiResult sudApiResult = getAllApi(env);
        if (sudApiResult.getApi() == null || StrUtil.isEmpty(sudApiResult.getApi().getPushEvent())) {
            throw new RRException("获取接口地址失败");
        }
        String baseRequestUrl = sudApiResult.getApi().getPushEvent();

        // 2. 拼接请求参数
        SudPushEventRequest sudPushEventRequest = new SudPushEventRequest();
        sudPushEventRequest.setMgId(CommonConstant.WOLF_GAME_ID);
        sudPushEventRequest.setEvent(event);
        sudPushEventRequest.setTimestamp(String.valueOf(System.currentTimeMillis()));

        sudPushEventRequest.setData(data);
        String sign = getSign(sudPushEventRequest);
        String bodyContent = JSONObject.toJSONString(sudPushEventRequest);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        headers.put("Authorization", sign);
        return HttpUtils.doPostJson(baseRequestUrl, bodyContent, headers, 10);
    }
}
